<?php

namespace app\api\controller;

use app\api\controller\Sms;
use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\cost\Category;
use app\common\model\cost\Cost;
use app\common\model\report;
use app\common\model\Equipment;
use app\common\model\Hospital;
use app\common\model\work\Commission;
use app\common\model\work\Maintain;
use app\common\model\work\Offer;
use app\common\model\work\Project;
use app\common\model\work\Repair;
use app\common\model\work\Service;
use app\common\model\work\Survey;
use app\common\model\Workflow;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use \app\common\model\work\Warranty as WarrantyModel;

/**
 * 工单接口
 */
class Warranty extends Api
{
    protected $noNeedLogin = ['costType','details','workflow','seesign','mainten','report'];//,'engineerList'
    protected $noNeedRight = ['*'];
    /**
     * 新增 内部方案发送短信
     * */
    public function project_note(){
        $platform_mobile=\think\Config::get('site.platform_mobile');//平台电话
        if(!$this->request->param("warranty_id")) $this->error("工单id不能为空");
        $warrantry=WarrantyModel::with(["hospital" => function ($query) {
            $query->withField('id,name,mobile');
        },
            "sale"=>function ($query) {
                $query->withField('id,nickname,mobile');
            },
            "equipment"=>function ($query) {
                $query->withField('id,name');
            }])
            ->where(["warranty.id"=>$this->request->param("warranty_id")])
            ->find();
        $sms = new Sms();
        if(empty($warrantry["project_note"])){
            if(!empty($platform_mobile)){
                if(!empty($platform_mobile)){
                    $str = [
                        "wordID" => $warrantry["workID"],
                        "hospital_name" => $warrantry["hospital"]["name"],
                        "equi_name" => $warrantry["equipment"]["name"],
                        "sale" => $warrantry["sale"]["nickname"],
                    ];
                    $ret = $sms->hairsendSms($platform_mobile, $str, 'SMS_260490089');
                }
            }
            if(!empty($warrantry["sale_id"]) && !empty($warrantry["sale"]["mobile"])){
                $str = [
                    "wordID" => $warrantry["hospital"]["name"],//医院
                    "equiName" => $warrantry["equipment"]["name"],
                ];
                $ret = $sms->hairsendSms($warrantry["sale"]["mobile"], $str, 'SMS_260380091');
            }
            $warrantry->save(["project_note"=>1]);
            $this->success("发送成功");
        }else{
            $this->error("短信已发送");
        }
    }



    /**
     * 报修
     *
     */
    public function add()
    {
        $user = $this->auth->getUser();
        $data=[
          /*  ['product', 'require', '产品名称不能为空'],
            ['device', 'require', '设备名称不能为空'],*/
            ['describe', 'require', '问题描述不能为空'],
            ['equipment_id', 'require', '设备id不能为空'],
           /* ['contacts', 'require', '联系人不能为空'],
            ['mobile', 'require|regex:/^1\d{10}$/', '联系电话不能为空|联系电话格式错误']*/
        ];
        if(!empty($user["identity"])){
            if(!$this->request->param("hospital_id")) $this->error('提交失败：请选择医院' );
        }else{
            $data=array_merge($data,[['contacts', 'require', '联系人不能为空'],
                ['mobile', 'require|regex:/^1\d{10}$/', '联系电话不能为空|联系电话格式错误']]);
        }
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $time=time();
        //$param["warranty_time"]=$time;
        $param["createtime"]=$time;
        //$params["workID"]="11".date("y",time());
        if(empty($user["identity"])){
            $hospital=Hospital::where(["status"=>1])->where('FIND_IN_SET("'.$user["id"].'", user_ids)')->find();
            $param["hospital_id"]=$hospital["id"];
        }
        $equipment=Equipment::get($param["equipment_id"]);
        if(empty($equipment)) $this->error('设备不存在' );
        Db::startTrans();
        try {
            $WarrantyModel=new WarrantyModel();
            $param["user_id"]=$user["id"];
            $id=$WarrantyModel->allowField(true)->insertGetId($param);//新增工单
            $WarrantyModel->where(["id"=>$id])->update(["workID"=>"11".date("y",time()).$id]);
            /******************记录维修表 start******************************/
            $service=array(
                "warranty_id"=>$id,//工单id
                "user_id"=>$user["id"],//用户id
                "applytime"=>$time,//申请时间
                "status"=>0,//状态:0=申请维修,1=已完成,2=申请结单,3=待维修
                "createtime"=>$time,//创建时间
            );
            $service_id=Service::insertGetId($service);
            /******************记录维修表  end******************************/

            /******************添加工作流  start******************************/
            $workflow=array(
                "warranty_id"=>$id,//工单id
                "hospital_id"=>$param["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>8,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>$id,//类型id
                "title"=>"工单已创建",//标题
                "content"=>"您的工单已成功提交，平台审核通过将第一时间联系您。",//详情
                "createtime"=>$time,//创建时间
                "service_id"=>$service_id,//创建时间
            );
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('新增成功');
    }


    /**
     * 工单详情
     * */
    public function details(){
        if(!$this->request->param("warranty_id")) $this->error("工单id不能为空");
        $warrantry=WarrantyModel::with(["hospital" => function ($query) {
            $query->withField('id,name,mobile');
        }])
            ->where(["warranty.id"=>$this->request->param("warranty_id")])
            ->find();
        if($warrantry){
            $equipment=Equipment::get([$warrantry["equipment_id"]]);
            if(!empty($warrantry["createtime"]))$warrantry["createtime"]=date("Y年m月d日",$warrantry["createtime"]);
            if(!empty($warrantry["examinetime"]))$warrantry["examinetime"]=date("Y年m月d日",$warrantry["examinetime"]);
            if(empty($warrantry["type_data"])){
                //报修工单
                $service=Service::where(["warranty_id"=>$warrantry["id"]])->find();
            }
            if($warrantry["type_data"]==1){
                if($warrantry["status"]!=3){
                    //维保工单
               /* $service=Service::where("status != '1'")->where(["warranty_id"=>$warrantry["id"]])->order("servicetime")->find();*/
                //$service=Service::whereNotIn("status",[1,2])->where(["warranty_id"=>$warrantry["id"]])->order("servicetime")->find();
                $ok_service=Service::whereIn("status",[1,2])->where(["warranty_id"=>$warrantry["id"]])->order("servicetime","desc")->find();
                if(empty($ok_service)){
                    //没有已完成的维修
                   $service=Service::where(["warranty_id"=>$warrantry["id"]])->order("servicetime")->find();
                }else{
                    $ing_service=Db::query("select * from (
SELECT a.warranty_id,id,a.status,a.servicetime,(@rowno:=@rowno+1) as number
FROM yl_work_service a,(select (@rowno:=0)) b where warranty_id=".$warrantry["id"]." ORDER BY a.servicetime asc ) t where servicetime <=".strtotime(date('Y-m-d',time())."23:59:59")." order by number limit 1");
                    $service=$ok_service;
                    if(!empty($ing_service)){
                        $service=Service::get($ing_service[0]["id"]);
                    }
                    $service["status"]=3;
                }
               /* dump($service);die();
                $service=Service::whereTime("servicetime","<=", strtotime(date('Y-m-d',time())."23:59:59"))
                ->where(["warranty_id"=>$warrantry["id"]])->order("servicetime")->find();
                $service=Db::query("select * from (
SELECT a.warranty_id,a.status,a.servicetime,(@rowno:=@rowno+1) as number
FROM yl_work_service a,(select (@rowno:=0)) b where warranty_id=".$v["id"]." ORDER BY a.servicetime asc ) t");
               if (empty($service)) {
                   $service=Service::where(["warranty_id"=>$warrantry["id"]])->order("servicetime")->find();;
               }*/
                /*$service=Db::query("select * from (
SELECT a.warranty_id,a.status,a.servicetime,(@rowno:=@rowno+1) as number
FROM yl_work_service a,(select (@rowno:=0)) b where warranty_id=".$v["id"]." ORDER BY a.servicetime asc ) t where status ='0' limit 1");*/
                }else{
                    $service=Service::where(["warranty_id"=>$warrantry["id"]])->order("servicetime","desc")->find();
                }
                
                $service["surplus"]=Service::where(["warranty_id"=>$warrantry["id"]])->where("status ='1' or status='2'")->count();
                $service["surplus"]=$warrantry["number"]-$service["surplus"];
                /*新增 2023-5-9  lina 客户报修时间  start*/
                $custom_time=Db::name("report")->field("custom_time")->where(["warranty_id"=>$warrantry["id"],"service_id"=>$service["id"]])->find();
                $warrantry["custom_time"]=(!empty($custom_time)&&$custom_time["custom_time"]>0) ?date("Y-m-d H:i:s",$custom_time["custom_time"]):0;
                /*新增 2023-5-9  lina 客户报修时间  end*/
            }
            $warrantry["service"]=$service;
            $warrantry["equipment"]=$equipment;
            if (!empty($warrantry["images"])) $warrantry["images"]=explode(",",$warrantry["images"]);
            /*新增 2022-11-28 李娜  start*/
            $project=Project::where(["warranty_id"=>$warrantry["id"]])->find();
            $warrantry["project_status"]=false;
            if(!empty($project)) $warrantry["project_status"]=true;
            /*新增 2022-11-28 李娜  end*/
        }
        $this->success('成功',$warrantry);
    }


    /***************************成本  start *********************************************************/
    /**
     * 成本类目
     * */
    public function costType(){
        $list=Category::order("weigh","desc")->select();
        $this->success('成功',$list);
    }
    /**
     * 新增成本
     * */
    public function addcost(){
        $user = $this->auth->getUser();
        if(empty($user["identity"])) $this->error('提交失败：医院方不能提交成本' );
        /*if(!$this->request->param("service_id")) $this->error('请输入维修id' );
        if(!$this->request->param("billing_data")) $this->error('请选择有无发票' );*/
        $validate = new \think\Validate([
            ['warranty_id', 'require', '工单id不能为空'],
            ['service_id', 'require', '请输入维修id'],
            ['billing_data', 'require', '请选择有无发票'],
            ['cost_category_id', 'require', '类目id不能为空'],
            ['money', 'require|/^[1-9]\d*(\.\d+)?$/', '报销金额不能为空|金额格式错误'],
            ['explain', 'require', '成本说明不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $param["user_id"]=$user["id"];
        $time=time();
        $param["createtime"]=$time;
        $warranty=WarrantyModel::where(["id"=>$param["warranty_id"]])->find();
        if(empty($warranty)) $this->error('提交失败：工单不存在' );
        /*2023-5-10 lina 注释状态判断*/
        /*if($warranty["status"]==3 && $warranty["warranty_time"]<time() && empty($warranty["type_data"])) $this->error('工单状态不允许添加成本');
        if($warranty["status"]==3 && (int)$warranty["type_data"]==1) $this->error('工单状态不允许添加成本');*/
        Db::startTrans();
        try {
            $model=new Cost();
            $id=$model->allowField(true)->insertGetId($param);
            /******************添加工作流  start******************************/
            $workflow=array(
                "warranty_id"=>$param["warranty_id"],//工单id
                "service_id"=>$param["service_id"],//工单id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>0,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>$id,//类型id
                "title"=>"更新了成本",//标题
                "content"=>"金额：".$param["money"]."
                ".$param["explain"],//详情
                "images"=>!$this->request->param("images")?'':$this->request->param("images"),//图片/视频
                "createtime"=>$time,//创建时间
            );
            if($warranty["type_data"]==1){
                $service=Service::find(["id"=>$param["service_id"]]);
                $workflow["number"]=$service["number"];
                $workflow["types_data"]=1;
            }
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * 成本列表
     * */
    public function costList(){
        if(!$this->request->param("warranty_id")) $this->error('提交失败：工单id' );
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $list=Cost::field("*,from_unixtime(cost.createtime, '%Y-%m-%d %H:%i:%S') createtime")
            ->with(["user"=>function($query){
                $query->withField('id,nickname,identity');
            }])
            ->order("createtime","desc")
            ->where(["cost.warranty_id"=>$this->request->param("warranty_id")])
            ->paginate(10,'',['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                if(!empty($v["images"])) $v["images"]=explode(",",$v["images"]);
            });
        $this->success('成功',$list);
    }
    /*************************** 成本  end *********************************************************/
    /***************************勘察记录  start *********************************************************/
    /**
     * 新增勘察记录
     * */
    public function addsurvey(){
        $user = $this->auth->getUser();
        if(empty($user["identity"])) $this->error('提交失败：医院方不能提交勘察记录' );
        if(!$this->request->param("service_id")) $this->error('请输入维修id' );
        $validate = new \think\Validate([
            ['warranty_id', 'require', '工单id不能为空'],
            ['service_id', 'require', '维修id不能为空'],
            ['result', 'require', '勘察结果不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $param["user_id"]=$user["id"];
        $time=time();
        $param["createtime"]=$time;
        $warranty=WarrantyModel::where(["id"=>$param["warranty_id"]])->find();
        if(empty($warranty)) $this->error('提交失败：工单不存在' );
        if($warranty["status"]==3 && $warranty["warranty_time"]<time() && empty($warranty["type_data"])) $this->error('工单状态不允许添加勘察记录');
        if($warranty["status"]==3 && (int)$warranty["type_data"]==1) $this->error('工单状态不允许添加勘察记录');
        Db::startTrans();
        try {
            $model=new Survey();
            $id=$model->allowField(true)->insertGetId($param);
            /******************添加工作流  start******************************/
            $workflow=array(
                "warranty_id"=>$param["warranty_id"],//工单id
                "service_id"=>$param["service_id"],//维修id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>4,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>$id,//类型id
                "title"=>"更新了勘察记录",//标题
                "content"=>$param["result"],//详情
                "images"=>!$this->request->param("images")?'':$this->request->param("images"),//图片/视频
                "createtime"=>$time,//创建时间
            );
            if($warranty["type_data"]==1){
                $service=Service::find(["id"=>$param["service_id"]]);
                $workflow["number"]=$service["number"];
                $workflow["types_data"]=1;
            }
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * 勘察列表
     * */
    public function surveyList(){
        if(!$this->request->param("warranty_id")) $this->error('提交失败：工单id' );
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $list=Survey::field("*,from_unixtime(survey.createtime, '%Y-%m-%d %H:%i:%S') createtime")
            ->with(["user"=>function($query){
                $query->withField('id,nickname,identity');
            }])
            ->order("createtime","desc")
            ->where(["warranty_id"=>$this->request->param("warranty_id")])
            ->paginate(10,'',['page' => $page, 'list_rows' => 10]);
        $this->success('成功',$list);
    }
    /*************************** 勘察  end *********************************************************/


    /***************************报价  start *********************************************************/
    /**
     * 新增报价
     * */
    public function addoffer(){
        $user = $this->auth->getUser();
        if(empty($user["identity"])) $this->error('提交失败：医院方不能提交报价' );
        if(!$this->request->param("warranty_id")) $this->error('请输入工单id' );
        if(!$this->request->param("service_id")) $this->error('请输入维修id' );
        //if(!$this->request->param("substance")) $this->error('请输入内容' );
        $param = $this->request->param();
        $params=[];
        $time=time();
        /*$validate = new \think\Validate([
            ['name', 'require', '名称不能为空'],
            ['money', 'require|/^[1-9]\d*(\.\d+)?$/', '报价不能为空|报价格式错误'],
            ['number', 'require', '数量不能为空'],
        ]);
        if (!$validate->check($param["substance"])) {
            $this->error('提交失败：' . $validate->getError());
        }*/
        $money=0;
        foreach ($param["substance"] as $k=>$v){
            $params[$k]["service_id"]=$param["service_id"];
            $params[$k]["warranty_id"]=$param["warranty_id"];
            $params[$k]["name"]=$v["name"];
            $params[$k]["money"]=$v["money"];
            $params[$k]["number"]=$v["number"];
            $params[$k]["user_id"]=$user["id"];
            $params[$k]["createtime"]=$time;
            $money+=$v["money"];
        }
        $all["substance"]=$params;
        $all["money"]=$money;
        $all1=["substance"=>json_encode($params),
            "money"=>$money,
            "name"=>$params[0]["name"],
            "user_id"=>$user["id"],
            "warranty_id"=>$param["warranty_id"],
            "service_id"=>$param["warranty_id"],
            "createtime"=>$time,
        ];
        $warranty=WarrantyModel::where(["id"=>$param["warranty_id"]])->find();
        if(empty($warranty)) $this->error('提交失败：工单不存在' );
        if($warranty["status"]==3 && $warranty["warranty_time"]<time() && empty($warranty["type_data"])) $this->error('工单状态不允许添加报价');
        if($warranty["status"]==3 && (int)$warranty["type_data"]==1) $this->error('工单状态不允许添加报价');
        Db::startTrans();
        try {
            $model=new Offer();
            $model->allowField(true)->insertGetId($all1);
            $id=$model->getLastInsID();
            /******************添加工作流  start  待完成******************************/
            $workflow=array(
                "warranty_id"=>$param["warranty_id"],//工单id
                "service_id"=>$param["service_id"],//维修id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>1,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>$id,//类型id
                "title"=>"更新了报价",//标题
                "content"=>json_encode($all),//详情
                "createtime"=>$time,//创建时间
            );
            if($warranty["type_data"]==1){
                $service=Service::find(["id"=>$param["service_id"]]);
                $workflow["number"]=$service["number"];
                $workflow["types_data"]=1;
            }
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * 报价列表
     * */
    public function offerList(){
        if(!$this->request->param("warranty_id")) $this->error('提交失败：工单id' );
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $list=Offer::field("id,offer.money,offer.image,from_unixtime(offer.createtime, '%Y-%m-%d %H:%i:%S') createtime")
            ->with(["user"=>function($query){
                $query->withField('id,nickname,identity');
            }])->where(["warranty_id"=>$this->request->param("warranty_id")])
            ->order("createtime","desc")
            ->paginate(10,'',['page' => $page, 'list_rows' => 10])
            /*->each(function ($v){
                $v["substance"]=json_decode($v["substance"],true);
            })*/;
        $all_money=Offer::sum("money");
        $this->success('成功',["list"=>$list,"all_money"=>$all_money]);
    }
    /*************************** 报价  end *********************************************************/


    /***************************方案 start *********************************************************/
    /**
     * 新增方案
     * */
    public function addproject(){
        $user = $this->auth->getUser();
        if(empty($user["identity"])) $this->error('提交失败：医院方不能提交方案' );
        if(!$this->request->param("service_id")) $this->error('请输入维修id' );
        $validate = new \think\Validate([
            ['warranty_id', 'require', '工单id不能为空'],
            ['service_id', 'require', '维修id不能为空'],
            ['project', 'require', '方案不能为空'],
            ['images', 'require', '图片不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $param["user_id"]=$user["id"];
        $time=time();
        $param["createtime"]=$time;
        $warranty=WarrantyModel::where(["id"=>$param["warranty_id"]])->find();
        if(empty($warranty)) $this->error('提交失败：工单不存在' );
        if($warranty["status"]==3 && $warranty["warranty_time"]<time() && empty($warranty["type_data"])) $this->error('工单状态不允许添加方案');
        if($warranty["status"]==3 && (int)$warranty["type_data"]==1) $this->error('工单状态不允许添加方案');
        Db::startTrans();
        try {
            $model=new Project();
            $id=$model->allowField(true)->insertGetId($param);
            /******************添加工作流  start  待完成******************************/
            $workflow=array(
                "warranty_id"=>$param["warranty_id"],//工单id
                "service_id"=>$param["service_id"],//维修id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>2,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>$id,//类型id
                "title"=>"更新了方案",//标题
                "content"=>$param["project"],//详情
                "images"=>$param["images"],//详情
                "createtime"=>$time,//创建时间
            );
            if($warranty["type_data"]==1){
                $service=Service::find(["id"=>$param["service_id"]]);
                $workflow["number"]=$service["number"];
                $workflow["types_data"]=1;
            }
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * 方案列表
     * */
    public function projectList(){
        if(!$this->request->param("warranty_id")) $this->error('提交失败：工单id' );
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $list=Project::field("*,from_unixtime(project.createtime, '%Y-%m-%d %H:%i:%S') createtime")
            ->with(["user"=>function($query){
                $query->withField('id,nickname,identity');
            }])
            ->order("createtime","desc")
            ->where(["warranty_id"=>$this->request->param("warranty_id")])
            ->paginate(10,'',['page' => $page, 'list_rows' => 10]) /*->each(function ($v){
                if(!empty($v["images"]))$v["images"]=explode(",",$v["images"]);
            })*/;
        $this->success('成功',$list);
    }
    /*************************** 方案  end *********************************************************/


    /*************************** 维修 start *********************************************************/
    /**
     * 新增维修
     * */
    public function addrepair(){
        $user = $this->auth->getUser();
        if(empty($user["identity"])) $this->error('提交失败：医院方不能提交维修记录' );
        if(!$this->request->param("service_id")) $this->error('请输入维修id' );
        $validate = new \think\Validate([
            ['warranty_id', 'require', '工单id不能为空'],
            ['service_id', 'require', '维修id不能为空'],
            ['repair', 'require', '记录不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $param["user_id"]=$user["id"];
        $time=time();
        $param["createtime"]=$time;
        $warranty=WarrantyModel::where(["id"=>$param["warranty_id"]])->find();
        if(empty($warranty)) $this->error('提交失败：工单不存在' );
        if($warranty["status"]==3 && $warranty["warranty_time"]<time() && empty($warranty["type_data"])) $this->error('工单状态不允许添加维修记录');
        if($warranty["status"]==3 && (int)$warranty["type_data"]==1) $this->error('工单状态不允许添加维修记录');
        Db::startTrans();
        try {
            $model=new Repair();
            $id=$model->allowField(true)->insertGetId($param);
            /******************添加工作流  start  待完成******************************/
            $workflow=array(
                "warranty_id"=>$param["warranty_id"],//工单id
                "service_id"=>$param["service_id"],//维修id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>3,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>$id,//类型id
                "title"=>"更新了维修记录",//标题
                "content"=>$param["repair"],//详情
                "images"=>!$this->request->param("images")? '':$this->request->param("images"),//图片/视频
                "createtime"=>$time,//创建时间
            );
            if($warranty["type_data"]==1){
                $service=Service::find(["id"=>$param["service_id"]]);
                $workflow["number"]=$service["number"];
                $workflow["types_data"]=1;
            }
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * 维修列表
     * */
    public function repairList(){
        if(!$this->request->param("warranty_id")) $this->error('提交失败：工单id' );
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $list=Repair::field("*,from_unixtime(repair.createtime, '%Y-%m-%d %H:%i:%S') createtime")
            ->with(["user"=>function($query){
                $query->withField('id,nickname,identity');
            }])
            ->order("createtime","desc")
            ->where(["warranty_id"=>$this->request->param("warranty_id")])
            ->paginate(10,'',['page' => $page, 'list_rows' => 10]);
        $this->success('成功',$list);
    }
    /*************************** 维修  end *********************************************************/

    /*************************** 保养  start *********************************************************/
    /**
     * 新增保养
     * */
    public function addmaintain(){
        $user = $this->auth->getUser();
        if(empty($user["identity"]))  $this->error('提交失败：医院方不能提交保养' );
        if(!$this->request->param("service_id")) $this->error('请输入维修id' );
        $validate = new \think\Validate([
            ['warranty_id', 'require', '工单id不能为空'],
            ['service_id', 'require', '维修id不能为空'],
            ['maintain', 'require', '内容不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $param["user_id"]=$user["id"];
        $time=time();
        $param["createtime"]=$time;
        $warranty=WarrantyModel::where(["id"=>$param["warranty_id"]])->find();
        if(empty($warranty)) $this->error('提交失败：工单不存在' );
        if ($warranty["type_data"]!=1) $this->error('提交失败：该订单不是维保订单' );
        if($warranty["status"]==3 && (int)$warranty["type_data"]==1) $this->error('工单状态不允许添加保养记录');
        Db::startTrans();
        try {
            $model=new Maintain();
            $id=$model->allowField(true)->insertGetId($param);
            /******************添加工作流  start  待完成******************************/
            $workflow=array(
                "warranty_id"=>$param["warranty_id"],//工单id
                "service_id"=>$param["service_id"],//维修id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>5,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>$id,//类型id
                "title"=>"更新了保养记录",//标题
                "content"=>$param["maintain"],//详情
                "createtime"=>$time,//创建时间
            );
            if($warranty["type_data"]==1){
                $service=Service::find(["id"=>$param["service_id"]]);
                $workflow["number"]=$service["number"];
                $workflow["types_data"]=1;
            }
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * 保养列表
     * */
    public function maintainList(){
        if(!$this->request->param("warranty_id")) $this->error('提交失败：工单id' );
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $list=Maintain::field("*,from_unixtime(maintain.createtime, '%Y-%m-%d %H:%i:%S') createtime")
            ->with(["user"=>function($query){
                $query->withField('id,nickname,identity');
            }])
            ->order("createtime","desc")
            ->where(["warranty_id"=>$this->request->param("warranty_id")])
            ->paginate(10,'',['page' => $page, 'list_rows' => 10]);
        $this->success('成功',$list);
    }
    /*************************** 保养  end *********************************************************/

    /**
     *
     * 工程师端首页
     * */
    public function engineerNum(){
        $user = $this->auth->getUser();
        if(empty($user["identity"])) $this->error('提交失败：医院方不能查看' );
        $list["all"]=WarrantyModel::count();//所有工单
        $list["ongoing"]=WarrantyModel::whereIn("status",["0",'1'])->count();//进行中
        $list["accepted"]=WarrantyModel::where(["status"=>'2'])->count();//待验收 "user_id"=>$user["id"],
        $list["day_add"]=WarrantyModel::whereTime('createtime', 'today')->count();//今日新增
        $list["maintenance"]=WarrantyModel::where(["type_data"=>'1'])->count();//维保工单
        $list["period"]=WarrantyModel::where(["status"=>'3',"type_data"=>'0'])->where("warranty_time >=".time())->count();//质保期内
        $list["done"]=WarrantyModel::where(["status"=>'3'])->count();//已完成
        $this->success('成功',$list);
    }

    /**
     * 工程师端工单列表页
     * */
    public function engineerList(){
        $user = $this->auth->getUser();
        /*$user["id"]=22;
        $user["identity"]=1;*/
        if(empty($user["identity"])) $this->error('提交失败：医院方不能查看' );
        $param = $this->request->param();
        $type = !$this->request->param('type')?'0':$this->request->param('type').'';//筛选 3全部 0报修 1维保
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $where=["warranty.type_data"=>$type];
        $where["engineer_id"]=$user["id"];
        $where1="1=1";
        /*2022-11-22 李娜 新增 start*/
        if(empty($this->request->param('status'))){
            $where1.=" and warranty.status <> '3'";
        }
        /*2022-11-22 李娜 新增 end*/
        if($user["identity"]==2){
            //销售
            unset($where["engineer_id"]);
            $where["sale_id"]=$user["id"];
        }
        if(!empty($this->request->param('status')) && $user["identity"]==2){
            unset($where["sale_id"]);
        }
        if(!empty($this->request->param('status')) && $user["identity"]==1){
            unset($where["engineer_id"]);
        }
        if ($type==3) unset($where["warranty.type_data"]);
        if($this->request->param('status')==4){
            //全部工单
            if(!empty($where["engineer_id"]))unset($where["engineer_id"]);
            if(!empty($where["sale_id"]))unset($where["sale_id"]);
        }
        if(!empty($this->request->param('search'))){
            $where1.=" and workID like '%".$param["search"]."%' or hospital.name like '%".$param["search"]."%' or equipment.name like '%".$param["search"]
                ."%' or  equipment.serial like '%".$param["search"]."%'";
        }
        if($this->request->param('status')==1) $where1.=" and (warranty.status='0' or warranty.status='1')";//进行中
        if($this->request->param('status')==2) $where1.=" and  warranty.type_data='0' and warranty.status='3' and warranty_time>=".time();//质保期内
        /*2022-11-22 李娜 新增 start*/
        /*if($this->request->param('status')==3) $where1.=" and warranty.status='3'";//已完成(改为保外)*/
        if($this->request->param('status')==3) $where1.=" and warranty.status='3' and warranty_time < ".time();//已完成(改为保外)
        if($this->request->param('status')==6) $where1.=" and warranty.status='3' and warranty_time > ".time();//保内
        /*2022-11-22 李娜 新增 end*/
        if($this->request->param('status')==5) $where1.=" and warranty.status='2'";//待验收
        $list=WarrantyModel::field("id,type_data,createtime,number,status,warranty_time,workID,is_loss,open_data,collect_data,surplus_num,maintain_num")
            ->with(["hospital" => function ($query) {
                $query->withField('id,name');
            },"engineer" => function ($query) {
                $query->withField('id,nickname');
            },"equipment"=>function ($query) {
                $query->withField("id,name,marking,serial");
            }
            ])
            ->where($where)
            ->where($where1)
            ->order("warranty.createtime","desc")
            ->paginate(10,'',['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                if($v["createtime"]) $v["createtime"]=date("Y-m-d H:i:s",$v["createtime"]);
                if($v["type_data"]==1){
                    //维保工单
                    $next=Db::query("select * from (
SELECT a.warranty_id,a.status,a.servicetime,(@rowno:=@rowno+1) as number
FROM yl_work_service a,(select (@rowno:=0)) b where warranty_id=".$v["id"]." ORDER BY a.servicetime asc ) t where status ='0' or status ='3' order by number limit 1");
                    //$next=Service::where(["warranty_id"=>$v["id"],"status"=>0,"type_data"=>1])->order("servicetime")->find();
                    /*dump($next);die();
                    $next=Service::where(["warranty_id"=>$v["id"],"status"=>0,"type_data"=>1])->order("servicetime")->find();*/
                    /*$all=Service::where(["warranty_id"=>$v["id"],"type_data"=>1])->whereIn("status",[1,2])->count();
                    $all=$all+1;*/
                    if($next){
                        $next=$next[0];
                        $v["next_time"]=date("Y-m-d",$next["servicetime"]);//下次维保时间
                    }else{
                        /*2023-1-4 修改 李娜 start*/
                        $v["next_time"]="维保时间已用完";
                    }
                    /*if(empty($next))$next["number"]=$v["number"];
                    $v["progress"]=$next["number"].'/'.$v["number"];//维保进度*/
                    $v["progress"]=$v["surplus_num"].'/'.$v["maintain_num"];//维保进度
                    /*2023-1-4 修改 李娜 end*/
                }else{
                    if ($v["status"]==3){
                        //已完成
                        $timediff = $v["warranty_time"]-time();
                        $days = intval($timediff/86400);
                        $v["days"]=$days;
                    }
                }
                /*2022-11-24 李娜 新增 start*/
                $v["commiss_sale"]=Commission::where(["type_data"=>'1','work_warranty_id'=>$v["id"]])->count();
                $v["commiss_eng"]=Commission::where(["type_data"=>'0','work_warranty_id'=>$v["id"]])->count();//工程师
                /*if(empty($this->request->param('status'))){
                }*/
                /*2022-11-24 李娜 新增 end*/
            });
        $this->success('成功',$list);
    }
    /**
     * 申请结单
     * */
    public function statement(){
        $user = $this->auth->getUser();
       /* $user["id"]=1;
        $user["identity"]=1;*/
        if(empty($user["identity"])) $this->error('提交失败：医院方不能提交结单' );
        $validate = new \think\Validate([
            ['warranty_id', 'require', '工单id不能为空'],
            ['service_id', 'require', '维修id不能为空'],
            ['contract_status', 'require', '合同状态不能为空'],
            ['service_type', 'require', '服务类型不能为空'],
            ['present_time', 'require', '到场时间不能为空'],
            ['ending', 'require', '维修结果及建议不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $warranty_id=$this->request->param('warranty_id');
        $service_id=$this->request->param('service_id');
        $param=$this->request->param();
        $warranty=WarrantyModel::find(["id"=>$warranty_id]);
        if(empty($warranty)) $this->error('工单不存在');
        if(($warranty["status"]==3 || $warranty["status"]==2) && $warranty["warranty_time"]<time() && empty($warranty["type_data"])) $this->error('工单状态不允许申请结单');
        /*2023-1-4 李娜  注释状态判断*/
        //if($warranty["status"]==3 && (int)$warranty["type_data"]==1) $this->error('工单状态不允许申请结单');
        /*2023-1-4 李娜  注释状态判断*/
        if(empty($warranty["type_data"])){
            //报修工单
            $survey=Service::where(["warranty_id"=>$warranty_id,"type_data"=>0])->find();
            if(empty($survey)) $this->error('工单不存在' );
        }
        if($warranty["type_data"]==1){
            //维保工单
            $survey=Service::where(["warranty_id"=>$warranty_id,"type_data"=>1,"id"=>$service_id])->order("servicetime","desc")->find();
            /*
             $survey=Service::where(["warranty_id"=>$warranty_id,"type_data"=>1,"id"=>$service_id])->whereIn("status",[0,3])->order("servicetime","desc")->find();
            */
            /*2023-1-4 李娜  新增保养次数判断 start*/
            if($param["service_type"]==1){
                //保养
                if($warranty["surplus_num"]<=0) $this->error('保养次数已用完');
            }
            /*2023-1-4 李娜  新增保养次数判断 end*/
            if(empty($survey)) $this->error('工单不存在' );

            /*2023-5-9 李娜  新增客户报修时间 start*/
            if(!$this->request->param('custom_time')) $this->error('请选择保修时间' );
            /*2023-5-9  李娜  新增客户报修时间 start*/
        }
        Db::startTrans();
        try {
            /** 维修表--下次维修时间表 修改 start**/
            $survey["status"]=2;
            $survey["contract_status"]=$param["contract_status"];
            $survey["service_type"]=$param["service_type"];
            $survey["present_time"]=strtotime($param["present_time"]." 00:00:00");
            $survey["ending"]=$param["ending"];
            $survey->save();
            /** 维修表--下次维修时间表 end**/
            /** 维修单修改 start**/
            if(empty($warranty["type_data"])){
                $warranty["status"]='2';
                $warranty->save();
            }
            /** 维修单修改 end**/
            /******************添加工作流  start  待完成******************************/
            $workflow=array(
                "warranty_id"=>$warranty_id,//工单id
                "service_id"=>$service_id,//维修id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>6,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>0,//类型id
                "title"=>"申请结单",//标题
                "content"=>"维修已完成，申请结单",//详情
                "createtime"=>time(),//创建时间
            );
            if($warranty["type_data"]==1){
                //$service=Service::find(["id"=>$service_id]);
                 $service=Db::query("select * from (
SELECT a.warranty_id,id,a.status,a.servicetime,(@rowno:=@rowno+1) as number
FROM yl_work_service a,(select (@rowno:=0)) b where warranty_id=".$warranty['id']." ORDER BY a.servicetime asc) t
where id=".$service_id.' limit 1');
                $workflow["number"]=$service[0]["number"];
                $workflow["types_data"]=1;
                /*2023-1-3 李娜  保养次数减1 start*/
                if($param["service_type"]==1){
                    //保养
                    $warranty["surplus_num"]=$warranty["surplus_num"]-1;
                    $warranty->save();
                }
                /*2023-1-3 李娜  保养次数减1 end*/
            }
                /****************** 新增 添加维修报告 strat***************************/
                $report_id=Db::name("report")->insertGetId([
                    "warranty_id"=>$warranty_id,//工单id
                    "service_id"=>$service_id,//维修id
                    "user_id"=>$user["id"],//用户id
                    "createtime"=>time(),//维修id
                    "type_data"=>$warranty["type_data"],//维修id
                    "contract_status"=>$param["contract_status"],//维修id
                    "service_type"=>$param["service_type"],//维修id
                    "status"=>2,//维修id
                    "ending"=>$param["ending"],//维修id
                    "present_time"=>strtotime($param["present_time"]." 00:00:00"),//维修id
                    "servicetime"=>$survey["servicetime"],
                    /*2023-1-5 新增 报修内容 李娜 start*/
                    'content'=>$param["content"]??"",
                    /*2023-1-5 新增 报修内容 李娜 end*/
                    /*2023-5-9 新增 报修时间 李娜 start*/
                    'custom_time'=>!$this->request->param('custom_time')?0:strtotime($param["custom_time"]),
                    /*2023-5-9 新增 报修时间 李娜 start*/
                ]);
                /****************** 新增 添加维修报告 end***************************/
                $workflow["report_id"]=$report_id;
            Workflow::create($workflow);
            /******************添加工作流  end******************************/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    /**
     * 客户签字
     * */
    public function signature(){
        $user=$this->auth->getUser();
        if(!$this->request->param('warranty_id')) $this->error("工单id为空");
        if(!$this->request->param('service_id')) $this->error("维修id为空");
        if(!$this->request->param('report_id')) $this->error("维修报告id为空");
        if(!$this->request->param('image')) $this->error("请上传图片");
        $warranty_id=$this->request->param('warranty_id');
        $service_id=$this->request->param('service_id');
        $image=$this->request->param('image');
        $warranty=WarrantyModel::find(["id"=>$warranty_id]);
        if(empty($warranty)) $this->error('工单不存在');
        if($warranty["status"]!=2 && empty($warranty["type_data"])) $this->error('工单状态错误');
        $time=time();
        /***   2022-6-27 修改 李娜 王云 start      **/
        /*$site_time=Config::get('site.warranty')?7:Config::get('site.warranty');*/
        /***   2023-1-12 修改 李娜 王云 修改7天为180天 start      **/
        //$site_time=$warranty["qa_time"]?$warranty["qa_time"]:7;
        $site_time=$warranty["qa_time"]?$warranty["qa_time"]:180;
        /***   2023-1-12 修改 李娜 王云 start      **/
        /***   2022-6-27 修改 李娜 王云 end      **/
        /*$i=$this->saveBase64('image',$image);
        dump($i);die();
        if($i["code"]==2000){
            $image=$i["data"];
        }else{
            $this->error($i["msg"]);
        }*/
        Db::startTrans();
        try {
            $service=Service::find(["id"=>$service_id]);
            if($service && $service["status"]!=1){
                $service_data=[
                    "image"=>$image,
                    "statementtime"=>$time,
                    "status"=>'1'
                ];
                if(empty($warranty["type_data"])){
                    $service_data["warranty_time"]=strtotime('+'.$site_time.' days', $time);
                }
                Service::where(["id"=>$service_id])->update($service_data);
            }
            $report_data=[
                "image"=>$image,
                "statementtime"=>$time,
                "warranty_time"=>strtotime('+'.$site_time.' days', $time),
                "status"=>'1',
                /*2023-1-10 新增 服务报告 start*/
                "report"=>$this->request->param('report')??""
                /*2023-1-10 新增 服务报告 end*/
            ];
                if(empty($warranty["type_data"])){
                    $report_data["warranty_time"]=strtotime('+'.$site_time.' days', $time);
                }
            Db::name("report")->where(["id"=>$this->request->param('report_id')])->update($report_data);
            if($warranty["type_data"]==1){
                /*$service=Service::find(["id"=>$service_id]);
                if(empty($warranty["type_data"]) || $service["number"]==$warranty["number"]){
                    $warranty->status='3';
                    $warranty->warranty_time=strtotime('+'.$site_time.' days', $time);
                    $warranty->save();
                }*/
            }else{
                $warranty->status='3';
                $warranty->warranty_time=strtotime('+'.$site_time.' days', $time);
                $warranty->save();
            }
            /******************添加工作流  start  ******************************/
            $workflow=array(
                "warranty_id"=>$warranty_id,//工单id
                "service_id"=>$service_id,//维修id
                "hospital_id"=>$warranty["hospital_id"],//医院id
                "user_id"=>$user["id"],//用户id
                "type_data"=>7,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                "type_id"=>0,//类型id
                "title"=>"工单已完成",//标题
                "content"=>"您的工单已结束，祝您生活愉快。",//详情
                "createtime"=>$time,//创建时间
            );
            if($warranty["type_data"]==1){
                //$service=Service::find(["id"=>$service_id]);
                $service=Db::query("select * from (
SELECT a.warranty_id,id,a.status,a.servicetime,(@rowno:=@rowno+1) as number
FROM yl_work_service a,(select (@rowno:=0)) b where warranty_id=".$warranty['id']." ORDER BY a.servicetime asc) t
where id=".$service_id.' order by number');
                $workflow["number"]=$service[0]["number"];
                $workflow["types_data"]=1;
            }
            Workflow::create($workflow);
            /******************添加工作流  end******************************/


            /***   2022-11-28 新增 李娜 王云 start      **/
            if(empty($warranty["qa_note"])){
                $str=[];
                $engineer=\app\common\model\User::field("nickname")->where(["id"=>$warranty["engineer_id"]])->find();
                $sale=\app\common\model\User::field("nickname")->where(["id"=>$warranty["sale_id"]])->find();
                if($warranty["type_data"]==1){
                    //维保工单
                    $service=Service::where(["warranty_id"=>$warranty["id"]])->where("servicetime > ".strtotime("+7 day"))->order("servicetime","desc")->find();
                    if(!empty($service)){
                        $str = [
                            "wordID" => $warranty["workID"],
                            "eng_name" => $engineer["nickname"],
                            "sale_name" => $sale["nickname"],
                        ];
                    }
                }else{
                    if($warranty["qa_time"]<7){
                        $str = [
                            "wordID" => $warranty["workID"],
                            "eng_name" => $engineer["nickname"],
                            "sale_name" => $sale["nickname"],
                        ];
                    }
                }
                if(!empty($str)){
                    $sms = new Sms();
                    $platform_mobile=\think\Config::get('site.platform_mobile');//平台电话
                    $warranty->save(["qa_note"=>1]);
                    $ret = $sms->hairsendSms($platform_mobile, $str, 'SMS_260580047');
                }
            }
            /***   2022-11-28 新增 李娜 王云 end      **/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    public function saveBase64($type="image",$image){
        ///接收参数  参数名叫image

        //目录的upload文件夹下
        $up_dir = "uploads/mine/signature/".date('Ymd', time()) . "/";  //创建目录
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777,true);
        }
        $base64_img = trim($image);
        dump($image);die();
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            dump($result);die();
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.time().'.'.$type;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    $img_path = str_replace('../../..', '', $new_file);
                    return json(array('code'=>20000,'data'=>$img_path,'msg'=>'成功'));
                }else{
                    return json(array('code'=>20001,'data'=>'','msg'=>'图片上传失败'));
                }
            }else{
                //文件类型错误
                return json(array('code'=>1,'data'=>'','msg'=>'图片上传类型错误'));
            }
        }

    }

    /************************ 医院端 start ***************************************************/
    /**
     * 医院端最新工单信息
     * */
    public function newest(){
        if(!$this->request->param('page')) $this->error('提交失败：医院方不能查看' );
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $user=$this->auth->getUser();
        $hospital=\app\common\model\Hospital::where('FIND_IN_SET("'.$user["id"].'", user_ids)')->find();
        if(empty($hospital))  $this->error('该用户未绑定医院');
        $list=Workflow::with(["user" => function ($query) {
            $query->withField('id,nickname');
        }])
            ->where(["hospital_id"=>$hospital["id"]])
            ->whereNotIn('workflow.type_data',['0','2'])
            ->whereTime("workflow.createtime",">=", '-14 days')
            ->order("workflow.createtime","desc")
            ->paginate(10,'',['page' => $page, 'list_rows' => 10]);
        $this->success('成功',$list);
    }

    /**
     *最新工单详情
     * */
    public function newestDetails(){
        if(!$this->request->param('workflow_id')) $this->error("工作流id为空");
        $workflow_id=$this->request->param('workflow_id');
        /*$user=$this->auth->getUser();
        $user["id"]=1;
        $hospital=\app\common\model\Hospital::where('FIND_IN_SET("'.$user["id"].'", user_ids)')->find();
        if(empty($hospital))  $this->error('该用户未绑定医院');*/
        $list=Workflow::with(["warranty" => function ($query) {
            $query->withField("createtime,examinetime,product,device,system_number,software_version,describe,images,workID");
        },"hospital" => function ($query) {
            $query->withField('id,name');
        },"user"=>function ($query) {
            $query->withField("id,nickname");
        }])
            ->whereNotIn('workflow.type_data',['0','2'])
            ->where(["workflow.id"=>$workflow_id])
            ->order("createtime","desc")
            ->find();
        if(!empty($list)){
            if(!empty($list["warranty"]["createtime"])) $list["warranty"]["createtime"]=date("Y-m-d",$list["warranty"]["createtime"]);
            if(!empty($list["warranty"]["examinetime"])) $list["warranty"]["examinetime"]=date("Y-m-d",$list["warranty"]["examinetime"]);
            if(!empty($list["warranty"]["images"])) $list["warranty"]["images"]=explode(",",$list["warranty"]["images"]);
            /*if($list["type_data"]==1){
                //报价
                $list["content"]=json_decode($list["content"],true);
            }*/
            if(empty($list["status"])){
                Workflow::where(["id"=>$list["id"]])->update(["status"=>'1']);
            }
        }
        $this->success('成功',$list);
    }
    /**
     * 工单工作流
     * */
    public function workflow(){
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        if(!$this->request->param('warranty_id')) $this->error("工单id为空");
        $warranty_id=$this->request->param('warranty_id');
        $list=Workflow::with(["warranty" => function ($query) {
            $query->withField("createtime,examinetime,product,device,system_number,software_version,describe,images,status,number,type_data,equipment_id");
        },"hospital" => function ($query) {
            $query->withField('id,name');
        },"user" => function ($query) {
            $query->withField('id,nickname');
        }])->field("a.name,a.marking,a.serial,a.enclosure,a.software_version,workflow.*")
            ->join("equipment a","warranty.equipment_id=a.id","left")
            ->where(["workflow.warranty_id"=>$warranty_id])
            ->whereNotIn('workflow.type_data',['0','2'])
            ->order("createtime","desc")
            ->paginate(10,'',['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                if((int)$v["type_data"]==6){
                    //申请结单
                    if($v["type_data"]==1){
                        $v["progress"]=$v["number"]."/".$v["warranty"]["number"];
                        $v["surplus"]=$v["warranty"]["number"]-$v["number"];
                    }
                }
                /*if((int)$v["type_data"]==1){
                    //报价
                    $v["content"]=json_decode($v["content"],true);
                }*/
                /* if($v["type_data"]==7 && $v["title"]=="工单已完成"){
                     //已完成订单

                 }*/
                if(!empty($v["warranty"]["createtime"])) $v["warranty"]["createtime"]=date("Y-m-d",$v["warranty"]["createtime"]);
                if(!empty($v["warranty"]["examinetime"])) $v["warranty"]["examinetime"]=date("Y-m-d",$v["warranty"]["examinetime"]);
            });
        $this->success('成功',$list);
    }

    /**
     * 维保工单报修
     * */
    public function repair(){
        if(!$this->request->param('warranty_id')) $this->error("工单id为空");
        if(!$this->request->param('service_id')) $this->error("维修id为空");
        $warranty_id=$this->request->param('warranty_id');
        $warranty=WarrantyModel::where(["id"=>$warranty_id])->find();
        $service=Service::where(["warranty_id"=>$warranty_id,"id"=>$this->request->param('service_id')])->where("status !=3")->order("servicetime")->find();
        if(empty($warranty)) $this->error("工单不存在");
        if($warranty["type_data"]!=1) $this->error("该工单不是维保工单");
        if(!empty($service["applytime"])) $this->error("该工单已提交过报修");
        $service->applytime=time();
        $service->save();
    }
    /**
     * 维保工单
     * */
    public function hospList(){
        $user=$this->auth->getUser();
        //$user["id"]=13;
        if(!empty($user["identity"])) $this->error('非医院方不能查看' );
        $status = !$this->request->param('status')?0:$this->request->param('status');//筛选 3已完成 1进行中 2=待确认 0全部 4（已报修）
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        $hospital=Hospital::where(["status"=>1])->where('FIND_IN_SET("'.$user["id"].'", user_ids)')->find();
        if(empty($hospital)) $this->error('该用户不是医院账号' );
        $where=" warranty.hospital_id = ".$hospital["id"]." and type_data='".$this->request->param('type')."'";
        if(empty($this->request->param('type'))){
            if(!empty($status) && (int)$status!=4){
                $where.=" and warranty.status='".$status."'";
            }
            if($status==4){
                $where.=" and warranty.status='0'";
            }
        }else{
            if($this->request->param('status')==1) $where.=" and warranty.status='1'";//进行中
            if($this->request->param('status')==2) $where.=" and warranty.status='2'";//待确认
            if($this->request->param('status')==3) $where.=" and warranty.status='3'";//已完成
        }
        $list=WarrantyModel::field("id,workID,type_data,from_unixtime(warranty.createtime, '%Y-%m-%d %H:%i:%S') createtime,number,warranty.status,warranty.describe,warranty.warranty_time")
            ->with(["hospital" => function ($query) {
                $query->withField('id,name');
            },"engineer" => function ($query) {
                $query->withField('id,nickname');
            },"equipment"=>function ($query) {
                $query->withField("id,name,marking,serial");
            }
            ])
            ->order("warranty.createtime","desc")
            ->where($where)
            ->paginate(10,'',['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                if(empty($v["type_data"])){
                    //报修工单
                    $service=Service::where(["warranty_id"=>$v["id"]])->find();
                    if ($v["status"]==3){
                        //已完成
                        $timediff = $v["warranty_time"]-time();
                        $days = intval($timediff/86400);
                        $v["days"]=$days;
                    }
                }
                if($v["type_data"]==1){
                    //维保工单
                    $service=Service::where("status != '3'")->where(["warranty_id"=>$v["id"]])->order("servicetime")->find();
                    $service["surplus"]=Service::where("status != '3'")->where(["warranty_id"=>$v["id"]])->count();
                    $service["surplus"]=$v["number"]-$service["surplus"];
                }
                $v["service"]=$service;
            });
        $this->success('成功',$list);
    }
    /**
     * 查看签字
     * */
    /*public function seesign(){
        if(!$this->request->param("service_id")) $this->error('维修id为空' );
        $service_id=$this->request->param("service_id");
        $list=Service::alias("a")
            ->field("a.id,a.warranty_id,a.type_data,a.number senumber,a.contract_status,a.service_type,from_unixtime(a.present_time, '%Y-%m-%d') present_time,a.ending,a.image,a.status,b.user_id,
            c.nickname,d.software_version,f.name equipment_name,f.marking equipment_marking,f.serial,d.describe,d.workID,f.software_version,d.number,d.warranty_time,d.images,from_unixtime(d.createtime, '%Y-%m-%d  %H:%i:%S') createtime,e.name")
            ->join("workflow b","a.id=b.service_id","left")
            ->join("user c","b.user_id=c.id","left")
            ->join("work_warranty d","b.warranty_id=d.id","left")
            ->join("hospital e","d.hospital_id=e.id","left")
            ->join("equipment f","f.id=d.equipment_id","left")
            ->where(["a.id"=>$service_id])
            ->find();
        if(!empty($list)){
            if( !empty($list["images"])) $list["images"]=explode(",",$list["images"]);
            if( !empty($list["warranty_time"])) $list["warranty_time"]=date("Y-m-d H:i:s",$list["warranty_time"]);
            $list["time"]=date("Y-m-d",time());
            if($list["type_data"]==1){
                //维保工单
                $next=Service::field("from_unixtime(servicetime, '%Y-%m-%d') servicetime,number")->where("id >".$list["id"])
                    ->where(["warranty_id"=>$list["warranty_id"]])->order("servicetime")->find();
                if(!empty($next)){
                    $list["next_time"]=$next["servicetime"];
                    $list["next_number"]=$next["number"];
                }
                $list["next_string"]=$list["senumber"].'/'.$list["number"];
            }
        };
        if($list){
            $list["project"]=Project::field("project")->where(["warranty_id"=>$list["warranty_id"]])->select();
            $list["repair"]=Repair::field("repair")->where(["warranty_id"=>$list["warranty_id"]])->select();
        }
        $this->success('成功',$list);
    }*/
     public function seesign(){
        if(!$this->request->param("service_id") &&  !$this->request->param("report_id")) $this->error('维修id为空' );
        if(true){
            //b.user_id,
            $id=$this->request->param("report_id")?$this->request->param("report_id"):$this->request->param("service_id");
            $list=Db::name("report")->alias("a")
                ->field("a.content,a.createtime re_time,a.statementtime,a.id,a.report,a.warranty_id,a.service_id,a.type_data,a.contract_status,a.service_type,from_unixtime(a.present_time, '%Y-%m-%d') present_time,a.ending,a.image,a.status,
            a.custom_time,c.nickname,d.software_version,f.name equipment_name,f.marking equipment_marking,f.serial,d.describe,d.workID,f.software_version,d.number,d.warranty_time,d.images,from_unixtime(d.createtime, '%Y-%m-%d  %H:%i:%S') createtime,e.name")
                //->join("workflow b","a.service_id=b.service_id","left")
                ->join("user c","a.user_id=c.id","left")
                ->join("work_warranty d","a.warranty_id=d.id","left")
                ->join("hospital e","d.hospital_id=e.id","left")
                ->join("equipment f","f.id=d.equipment_id","left")
                ->where(["a.id"=>$id])
                ->find();
        }else{
            $service_id=$this->request->param("service_id");
            $list=Service::alias("a")
                ->field("a.id,a.statementtime,a.warranty_id,a.type_data,a.number senumber,a.contract_status,a.service_type,from_unixtime(a.present_time, '%Y-%m-%d') present_time,a.ending,a.image,a.status,b.user_id,
            c.nickname,d.software_version,f.name equipment_name,f.marking equipment_marking,f.serial,d.describe,d.workID,f.software_version,d.number,d.warranty_time,d.images,from_unixtime(d.createtime, '%Y-%m-%d  %H:%i:%S') createtime,e.name")
                ->join("workflow b","a.id=b.service_id","left")
                ->join("user c","b.user_id=c.id","left")
                ->join("work_warranty d","b.warranty_id=d.id","left")
                ->join("hospital e","d.hospital_id=e.id","left")
                ->join("equipment f","f.id=d.equipment_id","left")
                ->where(["a.id"=>$service_id])
                ->find();
        }
        if(!empty($list)){
            if( !empty($list["images"])) $list["images"]=explode(",",$list["images"]);
            if( !empty($list["warranty_time"])) $list["warranty_time"]=date("Y-m-d H:i:s",$list["warranty_time"]);
            $list["time"]=date("Y-m-d",time());
            if($list["type_data"]==1){
                //维保工单
                /*$next=Service::field("from_unixtime(servicetime, '%Y-%m-%d') servicetime,number")->where("id >".$list["id"])
                    ->where(["warranty_id"=>$list["warranty_id"]])->order("servicetime")->find();*/
                $next=Db::query("select * from (
SELECT a.warranty_id,id,a.status,a.servicetime,(@rowno:=@rowno+1) as number
FROM yl_work_service a,(select (@rowno:=0)) b where warranty_id=".$list["id"]." ORDER BY a.servicetime asc ) t where (status ='0' or status ='3')
 and id=".$list["service_id"].' order by number limit 1');
                /*新增 2023-5-9  lina 客户报修时间  start*/
               /* $custom_time=Service::field("custom_time")->where(["id"=>$list["service_id"]])->find();
                $list["custom_time"]=(!empty($custom_time)&&$custom_time["custom_time"]>0) ?date("Y-m-d H:i:s",$custom_time["custom_time"]):0;*/
                $list["custom_time"]=$list["custom_time"]>0 ?date("Y-m-d H:i:s",$list["custom_time"]):0;
                /*新增 2023-5-9  lina 客户报修时间  end*/
                if(!empty($next)){
                    $next=$next[0];
                    $list["next_time"]=$next["servicetime"];
                    $list["next_number"]=$next["number"];
                }else{
                    $next["number"]=1;
                }
                $list["next_string"]=$next["number"].'/'.$list["number"];
            }
        };
        if($list){
            $list["project"]=Project::field("project")
                ->where(["warranty_id"=>$list["warranty_id"]])->select();
            $where="createtime <".$list["re_time"];
            if($list["statementtime"]){
                $where="createtime <".$list["statementtime"];
            }
            $list["repair"]=Repair::field("repair")
                ->where($where)
                ->where(["warranty_id"=>$list["warranty_id"]])
                ->order("createtime","desc")->limit(1)
                ->select();
        }
        $this->success('成功',$list);
    }
    /************************ 医院端 end ***************************************************/


    /*新增*/
    /*
     * 维保记录
     * */
    public function mainten(){
        $page = !$this->request->param('page')?1:$this->request->param('page');//页
        if(!$this->request->param("warranty_id")) $this->error('工单id为空' );
        /*$list=Service::field("id,warranty_id,type_data,statementtime,status")
            ->where(["warranty_id"=>$this->request->param("warranty_id")])
            ->whereIn("status",['1','2'])
            ->order("createtime","desc")
            ->paginate(10,'',['page' => $page, 'list_rows' => 10]);*/
            $list=Db::name("report")
                ->field("id report_id,service_id id,warranty_id,type_data,statementtime,from_unixtime(statementtime, '%Y-%m-%d %H:%i:%S') statementtime_text,status")
            ->where(["warranty_id"=>$this->request->param("warranty_id")])
            ->whereIn("status",['1','2'])
            ->order("createtime","desc")
            ->paginate(10,'',['page' => $page, 'list_rows' => 10]);
        $this->success('成功',$list);
    }
    
    /**
    *新增 2022-7-25
    */
    public function appoint(){
        $user=$this->auth->getUser();
        if($user["identity"]!=1) $this->error('该身份没有改派权限');
        $validate = new \think\Validate([
            ['warranty_id', 'require', '工单id不能为空'],
            ['engineer_id', 'require', '工程师id不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param=$this->request->param();
        if(empty($param["engineer_id"]))  $this->error("请选择工程师");
        $warranty=WarrantyModel::get($param["warranty_id"]);
        if(empty($warranty))$this->error('工单不存在');
        if($warranty["type_data"]==1)$this->error('工单不允许改派');
        if($warranty["status"]>=2)$this->error('工单状态不允许改派');
        if($warranty["engineer_id"]!=$user['id'])$this->error('只能修改指派给自己的工单');
        if($param["engineer_id"]==$warranty['engineer_id'])$this->error('订单已经指派给您了');
        Db::startTrans();
        try {
            $warranty->save(["engineer_id"=>$param["engineer_id"]]);//修改工单指派的工程师
            Service::where(["warranty_id"=>$warranty["id"]])->update(["user_id"=>$param["engineer_id"]]);
            $equipment=Equipment::get(["id"=>$warranty["equipment_id"]]);
            $sms=new Sms();
            $equipment_user=[];
            $str=[
                "wordID"=>$warranty["workID"],
                "name"=>$equipment["name"],
            ];
            if($param["engineer_id"]!=$warranty["engineer_id"]){
                $equipment_user=\app\common\model\User::get($param["engineer_id"]);
            }
            if($equipment_user && $equipment_user["mobile"]){
                $ret = $sms->hairsendSms($equipment_user["mobile"],$str,'SMS_245150564');
            }
            Db::name("appoint")->insert(["engineer_id"=>$param["engineer_id"],"warranty_id"=>$warranty["id"],"sale_id"=>$warranty["sale_id"],"createtime"=>time(),"user_id"=>$user["id"]]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }


    /**
     * 更新所有维修报告的报修描述
     * */
    public function report(){
        $model=new \app\common\model\Report();
        $list=$model->select();
        $data=[];
        if(!empty($list)){
            foreach ($list as $k=>$v){
                $warranty=WarrantyModel::where(["id"=>$v["warranty_id"]])->find();
                if(!empty($warranty)){
                    $data[$k]["id"]=$v["id"];
                    $data[$k]["content"]=$warranty["describe"];
                }
            }
            $model->saveall($data);
        }
    }
    /**
     * 维修服务报告
     * */
    public function edit_report(){
        if(!$this->request->param("id")) $this->error('服务报告id为空' );
        if(!$this->request->param("report")) $this->error('服务报告为空' );
        $report=\app\common\model\Report::get($this->request->param("id"));
        if(empty($report)) $this->error("服务报告不存在");
        $report_base64=$this->imgtobase64($this->request->param("report"));
        $report->save(["report"=>$this->request->param("report"),"report_base64"=>$report_base64]);
        $this->success('成功');
    }
    private function imgtobase64($img='', $imgHtmlCode=true)
    {
        if(strstr($img,"http")){
            $img="http".substr($img,5);
        }
        $imageInfo = getimagesize($img);
        $base64 = "" . chunk_split(base64_encode(file_get_contents($img)));
        return 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));;
    }
}
